<?php if (!defined('FIT_PATH')) exit('No direct script access allowed');
/**
 * @copyright 2009 - 2011 Bincent.com. All Rights Reserved.
 * @license http://www.apache.org/licenses/LICENSE-2.0
 * @package	FitPHP
 * @subpackage library
 * 
 * @author Hongbin Hsu <hongbin.hsu@gmail.com> Initial.
 * @version $Id: library/log.php 1.0 2010-12-03 23:03 hongbin.hsu $
 */
 
// ------------------------------------------------------------------------

class Library_Log
{
	public $enabled = true;
	public $log_path = 'data/log';				//日志存放目录
	public $log_file_ext = '.txt';				//日志记录文件类型
	public $log_date_format = 'Y-m-d H:i:s';	//日志时间格式
	public $log_threshold = 0;					//记录日志级别
	
	private $levels	= array('error'=>'1', 'debug'=>'2', 'info'=>'3', 'all'=>'4');

	//----------------------------------------------------------
	/**
	 * 日志构造
	 *
	 * @param array $config
	 */
	public function __construct($config){
		
		foreach ($config as $key => $value){
			if (isset($key) && !empty($value)) {
				$this->$key = $value;
			}
		}
		
		$log_path = APP_PATH.DIRECTORY_SEPARATOR;
		$log_path .= trim($this->log_path, '/').DIRECTORY_SEPARATOR;
		
		if (is_dir($log_path) && is_really_writable($log_path)){
			$this->log_path = $log_path;
		}else{
			$this->enabled = false;
		}
	}
	
	//----------------------------------------------------------
	/**
	 * 记录日志
	 *
	 * @param string $msg
	 * @param string $level
	 * @return bool
	 */
	public function write_log($msg, $level = 'error'){
		if (!$this->enabled) { return false; }
		
		if (!isset($this->levels[$level]) || ($this->levels[$level] > $this->log_threshold))
		{
			return false;
		}
		
		$level = strtolower($level);
		$filepath = $this->log_path.'log-'.date('Y-m-d').$this->log_file_ext;
		
		if (!file_exists($filepath)){
			return false;
		}
		
		if (!$fp = @fopen($filepath, FOPEN_WRITE_CREATE)){
			return false;
		}
		
		$message = $level.' '.(($level == 'info') ? ' -' : '-').' '.date($this->log_date_format). ' --> '.$msg."\n";
		
		flock($fp, LOCK_EX);	
		fwrite($fp, $message);
		flock($fp, LOCK_UN);
		fclose($fp);
	
		@chmod($filepath, FILE_WRITE_MODE); 		
		return true;
	}
}